package com.tuanzi.loan.web.bean.family;

import com.tuanzi.loan.business.entity.family.LoanChannelNdInfo;
import com.tuanzi.loan.business.service.family.LoanChannelNdInfoService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.family.LoanChannelNdInfoRequest;
import com.tuanzi.loan.vo.response.family.LoanChannelNdInfoResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.family.LoanChannelNdInfoLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanChannelNdInfoListBean extends JSFListingBean<LoanChannelNdInfoRequest, LoanChannelNdInfoResponse> {

    private static final long serialVersionUID = -4042919692993482039L;

    @Autowired
    private LoanChannelNdInfoService loanChannelNdInfoService;

    @PostConstruct
    private void init() {
        initLazyDataModel();
    }

    private void initLazyDataModel() {
        $ = new LoanChannelNdInfoRequest();
        this.lazyDataModel = new LoanChannelNdInfoLazyDataModel($);
    }

    public void batchAdd(){
        Integer postNum = this.$.getPostNum();
        Integer preNum = this.$.getPreNum();
        String preStr = this.$.getPreStr();
        String postStr = this.$.getPostStr();
        if(null == postNum || null == preNum || StringUtils.isBlank(preStr)){
            addErrorMessage("信息不能留空，请填写");
            return;
        }
        if(preNum > postNum){
            addErrorMessage("起始编号不能大于终止编号");
            return;
        }

        boolean postStrBlank = StringUtils.isBlank(postStr);
        for (int i = preNum; i <= postNum; i++){
            LoanChannelNdInfo channelNdInfo = new LoanChannelNdInfo();
            channelNdInfo.setChannel_nd(preStr + i + (postStrBlank ? "" : postStr));
            loanChannelNdInfoService.saveOrUpdate(channelNdInfo);
        }
        addSuccessfullyMessage();
    }

    public void onDelete(Long id){
        LoanChannelNdInfo dbInfo = loanChannelNdInfoService.findOne(id);
        if(null == dbInfo){
            init();
            return;
        }
        loanChannelNdInfoService.delete(dbInfo);
        init();
        addSuccessfullyMessage();
    }

    public void onRest(){
        init();
    }

    public String toEdit(Long id){
        return redirect("/views/family/WholeSaleManage/largeNewChannelInfo.xhtml?id="+id);
    }

    public String toAdd(){
        return redirect("/views/family/WholeSaleManage/largeNewChannelInfo.xhtml");
    }

}
